﻿using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Encodings.Web;
using System.Text.Json;
using BootstrapBlazor.Components;
using CardMaker.Library.Models;
using Newtonsoft.Json;
using SQLite;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace CardMaker.Library.Services;
public static class CardTemplateStorageConstant {
    public const string VersionKey =
        nameof(CardTemplateStorageConstant) + "." + nameof(Version);

    public const int Version = 1;
}

public class CardTemplateStorage:ICardTemplateStorage {
    //路径
    public const string DbName = "CardTemplate.sqlite3";
    private SQLiteAsyncConnection? _connection;

    public static readonly string CardTemplateDbPath =
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder
                .LocalApplicationData), DbName);
    //数据库连接
    private SQLiteAsyncConnection Connection =>
        _connection ??= new SQLiteAsyncConnection(CardTemplateDbPath);

    public async Task CloseAsync() => await Connection.CloseAsync();

    //偏好存储
    private readonly IPreferenceStorage _preferenceStorage;

    public CardTemplateStorage(IPreferenceStorage preferenceStorage) {
        _preferenceStorage = preferenceStorage;
    }

    //实现基本功能
    public async Task InitializeAsync() {
        await Connection.CreateTableAsync<CardTemplate>();
        _preferenceStorage.Set(CardTemplateStorageConstant.VersionKey,
            CardTemplateStorageConstant.Version);
    }
    public bool IsInitialized =>
        _preferenceStorage.Get(CardTemplateStorageConstant.VersionKey,
            default(int)) == CardTemplateStorageConstant.Version;
    public Task<CardTemplate> GetCardTemplateAsync(int cardTemplateId) =>
        Connection.Table<CardTemplate>().FirstOrDefaultAsync(p => p.CardTemplateId == cardTemplateId);

    public async Task<IEnumerable<CardTemplate>> GetCardTemplatesAsync(Expression<Func<CardTemplate, bool>> where, int skip, int take) =>
        await Connection.Table<CardTemplate>().Where(where).Skip(skip).Take(take).ToListAsync();
    

    /*public async  Task AddCardTemplateAsync(CardTemplate cardTemplate, List<SideImage> sideImages, List<TextFrame> textFrames) {
        // 将 sideImages 和 textFrames 列表转换为 JSON 字符串
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
        string sideImagesJson = JsonSerializer.Serialize(sideImages, options);
        string textFramesJson = JsonSerializer.Serialize(textFrames, options);
        cardTemplate.SideImages = sideImagesJson;
        cardTemplate.TextFrames = textFramesJson;
        await Connection.InsertOrReplaceAsync(cardTemplate);
    }*/

    public async Task AddCardTemplateAsync(CardTemplate cardTemplate, List<SideImage> sideImages, List<TextFrame> textFrames)
    {
        // 将 sideImages 和 textFrames 列表转换为 JSON 字符串
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        };
        string sideImagesJson = JsonSerializer.Serialize(sideImages, options);
        string textFramesJson = JsonSerializer.Serialize(textFrames, options);
        cardTemplate.SideImages = sideImagesJson;
        cardTemplate.TextFrames = textFramesJson;
        await Connection.InsertOrReplaceAsync(cardTemplate);
    }

    public async Task<CardTemplate> CreateCardTemplate(CardTemplate cardTemplate, List<SideImage> sideImages, List<TextFrame> textFrames) {
        await AddCardTemplateAsync(cardTemplate, sideImages, textFrames);
        return await Connection.Table<CardTemplate>().FirstOrDefaultAsync(p=>p.TemplateName.Equals(cardTemplate.TemplateName));
    }//todo 为了获取自增ID返回值的妥协写法，有待改进

}
